package com.auxgroup.hr.front.site.co.performance;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.auxgroup.hr.front.site.inteceptor.SessionGain;
import com.auxgroup.hr.front.site.vo.performance.*;
import com.auxgroup.hr.front.site.vo.process.WfApelHdrReqVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.auxgroup.hr.front.commons.BaseRetCode;
import com.auxgroup.hr.front.commons.enums.WfActionTypeEnum;
import com.auxgroup.hr.front.commons.enums.WfStatusEnum;
import com.auxgroup.hr.front.commons.enums.WfTypeEnum;
import com.auxgroup.hr.front.commons.utils.DateUtils;
import com.auxgroup.hr.front.commons.vo.BaseResponseVO;
import com.auxgroup.hr.front.commons.vo.UserDTO;
import com.auxgroup.hr.front.dao.domain.JobCurrPrimary;
import com.auxgroup.hr.front.dao.domain.ProcessMapRespVO;
import com.auxgroup.hr.front.dao.domain.PsCAppStepInst;
import com.auxgroup.hr.front.dao.domain.PsCEpAppRstVw;
import com.auxgroup.hr.front.dao.domain.PsCEpDocVw;
import com.auxgroup.hr.front.dao.domain.PsCEpIntrvwTbl;
import com.auxgroup.hr.front.dao.domain.PsCEpTrvRole;
import com.auxgroup.hr.front.dao.domain.PsCWfApelHdr;
import com.auxgroup.hr.front.dao.domain.PsCWfEmpVw;
import com.auxgroup.hr.front.dao.repository.PsCEpTrvRoleRepository;
import com.auxgroup.hr.front.dao.repository.PsCWfEmpVwRepository;
import com.auxgroup.hr.front.dozer.IObjectMapper;
import com.auxgroup.hr.front.service.performance.PerformancePlanService;
import com.auxgroup.hr.front.service.performance.PerformanceResultService;
import com.auxgroup.hr.front.service.process.ProcessService;
import com.auxgroup.hr.front.site.co.BaseCO;
import com.auxgroup.hr.front.site.inteceptor.SessionGain;
import com.auxgroup.hr.front.site.vo.performance.IntrvwTblReqVO;
import com.auxgroup.hr.front.site.vo.performance.IntrvwTblRespVO;
import com.auxgroup.hr.front.site.vo.performance.IntrvwTbqQueryReqVO;
import com.auxgroup.hr.front.site.vo.performance.PerformanceResultPersonRespVO;
import com.auxgroup.hr.front.site.vo.performance.WfApelReqVO;
import com.auxgroup.hr.front.site.vo.performance.WfApelRespVO;
import com.auxgroup.hr.front.site.vo.process.WfApelHdrReqVO;
import com.auxgroup.hr.front.ws.ProcessApplyQueDTO;
import com.auxgroup.hr.front.ws.ProcessApproveQueDTO;

/**
 * 绩效结果
 * @author lv-PC
 *
 */
@RestController
@RequestMapping("${auxgroup.hr.contextPath}/perresult")
public class PerformanceResultCO extends BaseCO {

	@Autowired
	private PerformanceResultService  performanceResultService;
	
	@Autowired
	private PerformancePlanService  performancePlanService;
	
	@Autowired
	private PsCWfEmpVwRepository psCWfEmpVwRepository;
	
	@Autowired
	private PsCEpTrvRoleRepository psCEpTrvRoleRepository;
	
	@Autowired
	private ProcessService processService;
	
	@Resource(name = "dozerMapper")
	protected IObjectMapper objectMapper;
	
	/**
	 * 绩效结果列表(年月)
	 * @param year
	 * @param user
	 * @return
	 */
	@GetMapping("/list")
	public BaseResponseVO getResultList(String year,@SessionGain("user") UserDTO user){
		List<PsCEpAppRstVw> appRsts = performanceResultService.getResultList(user.getOprId(), year);
		if(appRsts!=null&&!appRsts.isEmpty()){
			List<PerformanceResultPersonRespVO> respVos = new ArrayList<PerformanceResultPersonRespVO>();
			PerformanceResultPersonRespVO respVo;
			for (PsCEpAppRstVw appRst : appRsts) {
				respVo = new PerformanceResultPersonRespVO();
				respVo.setEmplid(appRst.getEmplid());
				respVo.setGroupId(appRst.getcEpRankGroup());
				respVo.setGroupName(appRst.getDescr1());
				respVo.setLevel(appRst.getcEpGradeRevised());
				respVo.setRanking(appRst.getcEpRanking());
				respVo.setRate(appRst.getcEvaRateRevised());
				respVo.setScore(appRst.getcEpScoreRevised());
				respVo.setTempId(appRst.getcEpTemplate());
				respVo.setTempName(appRst.getDescr());
				respVo.setYearMonth(appRst.getcEpPeriodId());
				respVo.setDocid(appRst.getcEpAppraisalId());
				respVo.setYear(appRst.getYear());
				respVo.setVersion(appRst.getVersion());
				respVos.add(respVo);
			}
			return buildRespone(respVos,false);
		}
		return buildRespone();
	}
	
	
	/**
	 * 查询绩效申诉信息
	 * @param docid
	 * @param version
	 * @param year
	 * @param user
	 * @return
	 */
	@GetMapping("/getApelInfo")
	public BaseResponseVO getApelInfo(String docid,String version,String year,@SessionGain("user") UserDTO user){
		PsCEpAppRstVw appRst = performanceResultService.getAppRst(user.getOprId(), year, docid, version);
		if(appRst==null){
			return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL);
		}
		PsCWfApelHdr apelHdr = performanceResultService.getApelHdr(appRst.getcEpAppraisalId(), appRst.getVersion());
		WfApelRespVO respVo = new WfApelRespVO();
		respVo.setGroupName(appRst.getDescr1());
		respVo.setLevel(appRst.getcEpGradeRevised());
		respVo.setRanking(appRst.getcEpRanking());
		respVo.setRate(appRst.getcEvaRateRevised());
		respVo.setScore(appRst.getcEpScoreRevised());
		respVo.setRanking(appRst.getcEpRanking());
		respVo.setTempName(appRst.getDescr());
		if(apelHdr!=null){
			respVo.setName(apelHdr.getNameDisplay());
			respVo.setDept(apelHdr.getRsFullName());
			respVo.setEmplid(apelHdr.getEmplid());
			respVo.setJobDescr(apelHdr.getJobcodeDescr());
			respVo.setcCommunication(apelHdr.getcCommunication());
			respVo.setcComnuniteDt(apelHdr.getcComnuniteDt());
			respVo.setcApplyItems(apelHdr.getcApplyItems());
			respVo.setcApplyReason(apelHdr.getcApplyReason());
			respVo.setcTransactionNbr(apelHdr.getcTransactionNbr());
			respVo.setcWfStatus(apelHdr.getcWfStatus());
			respVo.setcHrAdvice(apelHdr.getcHrAdvice());
		}else{
			JobCurrPrimary primary = new JobCurrPrimary();
			primary.setEmplid(user.getEmplId());
			primary.setEmplRcd(new BigDecimal(0));
			PsCWfEmpVw emp = psCWfEmpVwRepository.findOne(primary);//获取个人信息内容
			
			respVo.setName(emp.getNameDisplay());
			respVo.setDept(emp.getRsFullName());
			respVo.setEmplid(emp.getEmplid());
			respVo.setJobDescr(emp.getJobcodeDescr());
		}
		return buildRespone(respVo,false);
	}
	
	/**
	 * 查询绩效面谈信息,从绩效结果中进入时调用
	 * @param docid
	 * @param version
	 * @param user
	 * @return
	 */
	@GetMapping("/getIntrvwInfo")
	public BaseResponseVO getIntrvwInfo(IntrvwTbqQueryReqVO reqVo, @SessionGain("user") UserDTO user){
		String docid = "";
		BigDecimal version = null;
		IntrvwTblRespVO respVo = new IntrvwTblRespVO();
		if(StringUtils.isNotBlank(reqVo.getcTransactionNbr())){
			String emplid = user.getEmplId();
			String wfType = WfTypeEnum.WF_STYPE_EPFF.getType();
			if(StringUtils.isNotBlank(reqVo.getEmplid())){
				emplid = reqVo.getEmplid();
				wfType = WfTypeEnum.WF_STYPE_EPFR.getType();
			}
			PsCEpDocVw docvw = performancePlanService.getepdoc(emplid, reqVo.getcTransactionNbr(),wfType);
			if(docvw==null){
				return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL);
			}
			PsCEpTrvRole role = performanceResultService.getEpTrvRoles(docvw.getcEpAppraisalId(), docvw.getVersion(), user.getEmplId());
			docid = docvw.getcEpAppraisalId();
			version = docvw.getVersion();
			respVo.setName(docvw.getName());
			respVo.setDept(docvw.getDeptDescr());
			respVo.setEmplid(docvw.getEmplid());
			respVo.setJobDescr(docvw.getJobcodeDescr());
			respVo.setGroupName(docvw.getDescr3());
			respVo.setLevel(docvw.getcEpGradeRevised());
			respVo.setRanking(docvw.getcEpRanking());
			respVo.setRate(docvw.getcEvaRateRevised());
			respVo.setScore(docvw.getcEpScoreRevised());
			respVo.setTempName(docvw.getDescr());
			respVo.setDocid(docvw.getcEpAppraisalId());
			respVo.setVersion(docvw.getVersion());
			if(role!=null){
				respVo.setcComments(role.getComments());
			}
		}else{
			PsCEpAppRstVw appRst = performanceResultService.getAppRst(user.getOprId(), reqVo.getYear(), reqVo.getDocid(), reqVo.getVersion());
			if(appRst==null){
				return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL);
			}
			docid = appRst.getcEpAppraisalId();
			version = appRst.getVersion();
			JobCurrPrimary primary = new JobCurrPrimary();
			primary.setEmplid(user.getEmplId());
			primary.setEmplRcd(new BigDecimal(0));
			PsCWfEmpVw emp = psCWfEmpVwRepository.findOne(primary);//获取个人信息内容
			
			respVo.setName(emp.getNameDisplay());
			respVo.setDept(emp.getRsFullName());
			respVo.setEmplid(emp.getEmplid());
			respVo.setJobDescr(emp.getJobcodeDescr());
			respVo.setGroupName(appRst.getDescr1());
			respVo.setLevel(appRst.getcEpGradeRevised());
			respVo.setRate(appRst.getcEvaRateRevised());
			respVo.setScore(appRst.getcEpScoreRevised());
			respVo.setRanking(appRst.getcEpRanking());
			respVo.setTempName(appRst.getDescr());
			respVo.setDocid(appRst.getcEpAppraisalId());
			respVo.setVersion(appRst.getVersion());
		}
		//获取面谈信息
		PsCEpIntrvwTbl intrvw = performanceResultService.getIntrvwTbl(docid, version);
		if(intrvw!=null){
			respVo.setcEpCpbPlan(intrvw.getcEpCpbPlan());
			respVo.setcEpDeficiencies(intrvw.getcEpDeficiencies());
			respVo.setcEpImprPlan(intrvw.getcEpImprPlan());
			respVo.setcEpReach(intrvw.getcEpReach());
			respVo.setcEpReqHelp(intrvw.getcEpReqHelp());
			respVo.setStatus(intrvw.getcIntrvwStatus());
		}
		return buildRespone(respVo,false);
	}
	
	/**
	 * 计划审批人
	 * @param docid
	 * @param version
	 * @return
	 */
	@GetMapping("/intrvwPlanMap")
	public BaseResponseVO getProcessMap(String docid,String version){
		List<List<PsCEpTrvRole>> trvRoles = performanceResultService.getIntrvwProcessMap(docid, new BigDecimal(version));
		if(trvRoles!=null&&!trvRoles.isEmpty()){
			ProcessMapRespVO respVo;
			List<ProcessMapRespVO> respVos;
			List<List<ProcessMapRespVO>> respVolist = new ArrayList<List<ProcessMapRespVO>>();
			for (List<PsCEpTrvRole> roles : trvRoles) {
				respVos = new ArrayList<ProcessMapRespVO>();
				for (PsCEpTrvRole role : roles) {
					respVo = new ProcessMapRespVO();
					JobCurrPrimary primary = new JobCurrPrimary();
					primary.setEmplid(role.getEmplid());
					primary.setEmplRcd(role.getEmplRcd());
					PsCWfEmpVw emp = psCWfEmpVwRepository.findOne(primary);//获取个人信息内容
					respVo.setComments(role.getComments());
					if(emp!=null){
						respVo.setEmplName(emp.getNameDisplay());//姓名
					}
					respVo.setLastupddttm(DateUtils.format(role.getLastupddttm(), DateUtils.FORMAT_DEFAULT));
					respVo.setcStepStatus(role.getcItrStatus());
					respVo.setDescr(role.getcEpRolename());
					respVos.add(respVo);
				}
				respVolist.add(respVos);
			}
			return buildRespone(respVolist,false);
		}
		return buildRespone();
	}
	
	
	
	/**
	 * 查询绩效申诉信息
	 * @param docid
	 * @param version
	 * @param year
	 * @param user
	 * @return
	 */
	@GetMapping("/getWfApelInfo")
	public BaseResponseVO getWfApelInfo(String cTransactionNbr,@SessionGain("user") UserDTO user){
		PsCWfApelHdr apelHdr = performanceResultService.getApelHdr(cTransactionNbr);
		if(apelHdr==null){
			return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL);
		}
		WfApelRespVO respVo = new WfApelRespVO();
		respVo.setName(apelHdr.getNameDisplay());
		respVo.setDept(apelHdr.getRsFullName());
		respVo.setEmplid(apelHdr.getEmplid());
		respVo.setJobDescr(apelHdr.getJobcodeDescr());
		respVo.setGroupName(performanceResultService.getGroupName(apelHdr.getcEpRankGroup()));
		respVo.setLevel(apelHdr.getcEpGradeRevised());
		respVo.setRate(apelHdr.getcEvaRateRevised());
		respVo.setScore(apelHdr.getcEpScoreRevised());
		respVo.setRanking(apelHdr.getcEpRanking());
		respVo.setTempName(performanceResultService.getTempName(apelHdr.getcEpTemplate()));
		respVo.setcCommunication(apelHdr.getcCommunication());
		respVo.setcComnuniteDt(apelHdr.getcComnuniteDt());
		respVo.setcApplyItems(apelHdr.getcApplyItems());
		respVo.setcApplyReason(apelHdr.getcApplyReason());
		respVo.setcTransactionNbr(apelHdr.getcTransactionNbr());
		respVo.setcWfStatus(apelHdr.getcWfStatus());
		respVo.setcHrAdvice(apelHdr.getcHrAdvice());
		//设置按钮权限
		PsCAppStepInst stepInst = processService.getStepInst(cTransactionNbr, user);
		if(stepInst!=null){
			respVo.setcApprovalSw(stepInst.getcApprovalSw());
			respVo.setcDenySw(stepInst.getcDenySw());
			respVo.setcPushbackAllSw(stepInst.getcPushbackAllSw());
			respVo.setcAddSw(stepInst.getcAddSw());
		}
		return buildRespone(respVo,false);
	}
	
	/**
	 * 保存绩效申诉
	 * @param reqVo
	 * @param user
	 * @return
	 */
	@PostMapping("/saveApelInfo")
	public BaseResponseVO saveApelInfo(WfApelReqVO reqVo, @SessionGain("user") UserDTO user){
		logger.info("saveApelInfo param:{}",reqVo);
        if(reqVo==null){
        	return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL.getRetCode(),"保存入参不能为空");
        }
        PsCEpAppRstVw appRst = performanceResultService.getAppRst(user.getOprId(), reqVo.getYear(), reqVo.getDocid(), reqVo.getVersion());
		if(appRst==null){
			return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL);
		}
		String cTransactionNbr = "";
		if(StringUtils.isBlank(reqVo.getcTransactionNbr())){
			cTransactionNbr = processService.getTranNum();
		}else{
			cTransactionNbr = reqVo.getcTransactionNbr();
		}
		
        PsCWfApelHdr apelHdr = objectMapper.map(reqVo, PsCWfApelHdr.class);
        apelHdr.setcTransactionNbr(cTransactionNbr);
        
        //保存补卡申请
        apelHdr = performanceResultService.saveApelHdr(apelHdr,appRst,user);
        if(apelHdr!=null&&"commit".equals(reqVo.getType())){
        	ProcessApplyQueDTO requestDTO = new ProcessApplyQueDTO();
        	if(WfStatusEnum.WF_STATUS_S.getStatus().equals(apelHdr.getcWfStatus())){
        		requestDTO.setC_ACTION_TYPE(WfActionTypeEnum.WF_ACTION_SUBMIT.getAction());
        	}else{
        		requestDTO.setC_ACTION_TYPE(WfActionTypeEnum.WF_ACTION_RESUBMIT.getAction());
        	}
            requestDTO.setC_TRANSACTION_NBR(cTransactionNbr);
            requestDTO.setC_USERID(user.getOprId());
            requestDTO.setC_WF_TYPE(WfTypeEnum.WF_STYPE_APEL.getType());
            Map<String, String> approveResult = processService.apply(requestDTO);
            if(approveResult==null||approveResult.isEmpty()){
    			return buildRespone(BaseRetCode.CODE_ERROR_PROCESS_APPLY_FAIL);
    		}
            if("0".equals(approveResult.get("C_MSG_CODE"))){
            	return buildRespone(cTransactionNbr);
            }else{
            	//只有初次发起时，发起失败才删除数据
            	if(WfStatusEnum.WF_STATUS_S.getStatus().equals(apelHdr.getcWfStatus())){
            		//流程发起失败，删除数据
            		performanceResultService.delApelHdr(cTransactionNbr);
            	}
            	return buildRespone(approveResult.get("C_MSG_CODE"), approveResult.get("C_MSG_TEXT"));
            }
        }
        return buildRespone();
	}
	
	
	
	/**
	 * 保存绩效面谈
	 * @param reqVo
	 * @param user
	 * @return
	 */
	@PostMapping("/saveIntrvwTbl")
	public BaseResponseVO saveIntrvwTbl(IntrvwTblReqVO reqVo,@SessionGain("user") UserDTO user){
		logger.info("saveIntrvwTbl param:{}",reqVo);
        if(StringUtils.isBlank(reqVo.getDocid())||StringUtils.isBlank(reqVo.getVersion())){
        	return buildRespone(BaseRetCode.CODE_ERROR_REQUEST_PARAM_NULL.getRetCode(),"保存入参不能为空");
        }
        PsCEpIntrvwTbl intrvwTbl = objectMapper.map(reqVo, PsCEpIntrvwTbl.class);
        intrvwTbl.setcEpAppraisalId(reqVo.getDocid());
        intrvwTbl.setVersion(new BigDecimal(reqVo.getVersion()));
        intrvwTbl.setEmplid(user.getEmplId());
        intrvwTbl.setEmplRcd(new BigDecimal(0));
        
        //保存面谈申请
        intrvwTbl = performanceResultService.saveIntrvwTbl(intrvwTbl, user, reqVo.getType());
		return buildRespone();
	}
	
	
	/**
	 * 绩效申诉审批
	 * @param reqVo
	 * @param user
	 * @param binding
	 * @return
	 */
	@PostMapping(value="/approveApel")
	public BaseResponseVO approveApel(WfApelHdrReqVO reqVo, @SessionGain("user") UserDTO user, BindingResult binding){
		// 表单校验
        super.assertValidation(binding);
        PsCWfApelHdr apelHdr = performanceResultService.getApelHdr(reqVo.getcTransactionNbr());
        if(apelHdr==null){
			return buildRespone(BaseRetCode.CODE_ERROR_PROCESS_NOT_EXIST);
		}
        //设置数据
        if(StringUtils.isNotBlank(reqVo.getcHrAdvice())){
        	apelHdr.setcHrAdvice(reqVo.getcHrAdvice());
        }
        //保存数据
        performanceResultService.saveApelHdr(apelHdr);
        //审批流程
        ProcessApproveQueDTO requestDTO = new ProcessApproveQueDTO();
        requestDTO.setC_ACTION_TYPE(reqVo.getActionType());
        requestDTO.setC_COMMENTS(reqVo.getcComments());
        requestDTO.setC_TRANSACTION_NBR(reqVo.getcTransactionNbr());
        requestDTO.setC_USERID(user.getOprId());
        requestDTO.setC_WF_TYPE(WfTypeEnum.WF_STYPE_APEL.getType());
        requestDTO.setAddUserids(reqVo.getAddUserIds());
        Map<String, String> approveResult = processService.approve(requestDTO);
        if(approveResult==null||approveResult.isEmpty()){
			return buildRespone(BaseRetCode.CODE_ERROR_PROCESS_APRROVE_FAIL);
		}
        if("0".equals(approveResult.get("C_MSG_CODE"))){
        	return buildRespone(BaseRetCode.CODE_SUCCESS);
        }else{
        	return buildRespone(approveResult.get("C_MSG_CODE"), approveResult.get("C_MSG_TEXT"));
        }
	}
	
	
	/**
	 * 绩效面谈审批
	 * @param reqVo
	 * @param user
	 * @param binding
	 * @return
	 */
	@PostMapping(value="/approveIntrvw")
	public BaseResponseVO approveIntrvw(IntrvwTblReqVO reqVo,@SessionGain("user") UserDTO user){
		if(StringUtils.isBlank(reqVo.getDocid())||StringUtils.isBlank(reqVo.getVersion())){
			return buildRespone(BaseRetCode.CODE_ERROR_PROCESS_NOT_EXIST);
		}
		PsCEpIntrvwTbl intrvwTbl = performanceResultService.getIntrvwTbl(reqVo.getDocid(), new BigDecimal(reqVo.getVersion()));
		if(intrvwTbl==null){
			return buildRespone(BaseRetCode.CODE_ERROR_PROCESS_NOT_EXIST);
		}
		intrvwTbl.setcEpCpbPlan(reqVo.getcEpCpbPlan());
		intrvwTbl.setcEpDeficiencies(reqVo.getcEpDeficiencies());
		intrvwTbl.setcEpImprPlan(reqVo.getcEpImprPlan());
		intrvwTbl.setcEpReach(reqVo.getcEpReach());
		intrvwTbl.setcEpReqHelp(reqVo.getcEpReqHelp());
		intrvwTbl = performanceResultService.saveIntrvwTbl(intrvwTbl, user, "save");
		PsCEpTrvRole role = performanceResultService.getEpTrvRoles(reqVo.getDocid(), new BigDecimal(reqVo.getVersion()), user.getEmplId());
		BigDecimal seqnbr = role.getSeqnbr();
		if(StringUtils.isNotBlank(reqVo.getcComments())){
			role.setComments(reqVo.getcComments());
			psCEpTrvRoleRepository.save(role);
		}
		if(StringUtils.isNotBlank(reqVo.getType())&&"APPROVE".equals(reqVo.getType())){
			Map<String, String> result =  performanceResultService.commitIntrvwService(intrvwTbl,seqnbr,user.getEmplId(), "APP");
			if(result!=null&&"A".equals(result.get("C_CHAR"))){
				return buildRespone();
			}else{
				return buildRespone(BaseRetCode.CODE_ERROR_SYS.getRetCode(), result.get("MESSAGE_TEXT"));
			}
		}
        return buildRespone();
	}
	
	
	
}
